<template>
  <div class="health-box" style="height: calc(100vh - 225px); overflow: hidden">
    <div class="title-box">
      <div class="title-item-left">
        <span class="text-icon" />
        体检信息
      </div>
    </div>
    <div v-if="relationTimeList.length > 0">
      <div style="display: flex; align-items: center; justify-content: center; height: 55px">
        <div style="display: flex; align-items: center; justify-content: center">
          <LeftCircleFilled
            @click="perTime"
            :style="{
              'font-size': '18px',
              cursor: 'pointer',
              color: relationTimePer ? '#C9CDD4' : ''
            }"
          />
        </div>
        <div style="display: flex; justify-content: flex-start; width: 550px; margin: 0 30px">
          <div
            :class="relationIndex == index ? 'pe-time-li action' : 'pe-time-li'"
            v-for="(item, index) in relationTime"
            @click="relationTimeHandle(item, index)"
            :key="index"
          >
            <span class="pe-time-year">{{ dayjs(item).format('YYYY') }}</span>
            <span class="pe-time-date">{{ dayjs(item).format('MM-DD') }}</span>
          </div>
        </div>
        <div style="display: flex; align-items: center; justify-content: center">
          <RightCircleFilled
            @click="nextTime"
            :style="{
              'font-size': '18px',
              cursor: 'pointer',
              color: relationTimeNext ? '#C9CDD4' : ''
            }"
          />
        </div>
      </div>
    </div>
    <div style="margin-top: 16px">
      <div style="display: flex; margin-bottom: 16px">
        <div style="margin-right: 36px; font-weight: 600">
          体检机构：
          <span class="orgName" v-if="List">
            {{ examInfoOrgName }}
          </span>
          <span v-else>-</span>
        </div>
        <div style="margin-right: 36px; font-weight: 600">
          体检报告：
          <span v-if="!examInfoUrl" style="font-size: 14px">暂无报告</span>
          <span
            v-else
            @click="seeFile"
            style="padding-left: 0; font-weight: 600; color: #165dff; cursor: pointer"
          >
            查看PDF报告
          </span>
        </div>
        <div style="font-weight: 600">
          健康管理报告：
          <span style="font-size: 14px" v-if="!pdfUrl">暂无报告</span>
          <span
            v-else
            @click="healthFile"
            style="padding-left: 0; font-weight: 600; color: #165dff; cursor: pointer"
            >查看PDF报告</span
          >
        </div>
      </div>

      <a-tabs v-model:activeKey="tabsIndex" type="card">
        <a-tab-pane :key="item" :tab="item" v-for="item in tabsData">
          <div style="height: calc(100vh - 440px); padding-right: 10px; overflow: hidden auto">
            <template v-if="tabsIndex == '主要异常结果'">
              <template v-for="vo in abnormalData" :key="JSON.stringify(vo)">
                <div class="abnormal-label">{{ vo.name }}</div>
                <template v-if="vo.name == '实验室检查'">
                  <a-table
                    size="small"
                    :dataSource="vo.list"
                    :columns="abnormalLab"
                    :pagination="false"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex == 'itemResult'">
                        {{ record.content.itemResult }}
                      </template>
                      <template v-else-if="column.dataIndex == 'itemResultUnit'">
                        {{ record.content.itemResultUnit }}
                      </template>
                      <template v-else-if="column.dataIndex == 'reference'">
                        {{ record.content.reference }}
                      </template>
                      <template v-else-if="column.dataIndex == 'resultFlag'">
                        <span v-if="!record.content.resultFlag">-</span>
                        <span v-else style="color: red">{{
                          record.content.resultFlag == 1 ? '↑' : '↓'
                        }}</span>
                      </template>
                    </template>
                  </a-table>
                </template>
                <template v-else>
                  <template v-for="voo in vo.data" :key="JSON.stringify(voo)">
                    <div class="group-label">【{{ voo.name }}】</div>
                    <div class="group-cont">
                      <template v-if="voo.list.length">
                        <div v-for="groupList in voo.list" :key="JSON.stringify(groupList)">
                          <span>{{ groupList.itemName }}：</span>
                          <span>{{ groupList.content.itemResult }}</span>
                        </div>
                      </template>
                      <template v-else>
                        <div>暂无数据</div>
                      </template>
                    </div>
                  </template>
                </template>
              </template>
              <template v-if="!abnormalData.length">
                <a-empty style="padding-top: 50px" />
              </template>
            </template>
            <template v-if="tabsIndex == '体格检查'">
              <a-table
                size="small"
                :dataSource="routineList"
                :columns="routineColumns"
                :loading="loading"
                :pagination="false"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex == 'peItemResult'">
                    <span v-if="record.qualitative == '0'" style="color: red">
                      {{ record.peItemResult }}
                    </span>
                    <span v-else>{{ record.peItemResult }}</span>
                  </template>
                  <template v-else-if="column.dataIndex == 'peItemName'">
                    <span @click="peItemLabel(record)" class="pe-item-col">{{
                      record.peItemName
                    }}</span>
                  </template>
                </template>
              </a-table>
            </template>
            <template v-if="tabsIndex == '实验室检查'">
              <a-table
                size="small"
                :dataSource="testList"
                :columns="testColumns"
                :loading="loading"
                :pagination="false"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex == 'peItemResult'">
                    <span v-if="record.qualitative == '0'" style="color: red">
                      {{ record.peItemResult }}
                    </span>
                    <span v-else>{{ record.peItemResult }}</span>
                  </template>
                  <template v-else-if="column.dataIndex == 'peItemName'">
                    <span @click="peItemLabel(record)" class="pe-item-col">{{
                      record.peItemName
                    }}</span>
                  </template>
                </template>
              </a-table>
            </template>
            <template v-if="tabsIndex == '其他辅助检查'">
              <a-table
                size="small"
                :dataSource="inspectList"
                :columns="inspectColumns"
                :loading="loading"
                :pagination="false"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex == 'peItemResult'">
                    <pre
                      :style="{
                        'margin-bottom': 0,
                        'font-size': '14px',
                        fontFamily: 'Arial',
                        'word-wrap': 'break-word',
                        'white-space': 'pre-wrap',
                        color: 'rgba(0, 0, 0, 88%)'
                      }"
                      >{{ record.peItemResult }}</pre
                    >
                  </template>
                  <template v-else-if="column.dataIndex == 'peItemName'">
                    <span @click="peItemLabel(record)" class="pe-item-col">{{
                      record.peItemName
                    }}</span>
                  </template>
                  <template v-else-if="column.dataIndex == 'peItemSmry'">
                    <pre
                      :style="{
                        'margin-bottom': 0,
                        'font-size': '14px',
                        fontFamily: 'Arial',
                        'word-wrap': 'break-word',
                        'white-space': 'pre-wrap',
                        color: record.qualitative === '0' ? 'red' : 'rgba(0, 0, 0, 88%)'
                      }"
                      >{{ record.peItemSmry }}</pre
                    >
                  </template>
                </template>
              </a-table>
            </template>
          </div>
        </a-tab-pane>
      </a-tabs>
      <!-- <a-table
        class="exam-table"
        size="small"
        :columns="columns"
        :dataSource="examInfoData"
        :loading="loading"
        :pagination="false"
        :scroll="{ x: 'calc(1300px + 50%)' }"
      >
      </a-table> -->
    </div>

    <PeHistory ref="peHistory" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { LeftCircleFilled, RightCircleFilled } from '@ant-design/icons-vue'
import { getPatientCheckUpTime } from '@/api/patientMana/index'
import { tableRowSpan } from '@/utils/tools'
import { getHealthReportStatus } from '@/api/healthManaWorkbench'
import PeHistory from './peHistory.vue'

const relationIndex = ref(0)
const relationSelTime = ref('')
const relationTime = ref([])
const relationData: any = ref([])
const relationTimePage = ref(1)
const relationTimePer = ref(true)
const relationTimeNext = ref(false)
const relationTimeList: any = ref([])
const patientEmpi = ref()

const examInfoData = ref([])
const List = ref()
const loading = ref(false)
const abnormalData = ref<any>([])
const testList = ref([])
const inspectList = ref([])
const routineList = ref([])
const testColumns = ref([
  {
    title: '体检项目组合名称',
    dataIndex: 'peItemGroupName',
    key: 'peItemGroupName',
    align: 'left',
    customCell: (record, index, column) => {
      return tableRowSpan(record, index, column, testList.value)
    }
  },
  {
    title: '体检项目名称',
    dataIndex: 'peItemName',
    key: 'peItemName',
    align: 'left'
  },
  {
    title: '结果',
    dataIndex: 'peItemResult',
    key: 'peItemResult',
    align: 'left'
  },
  {
    title: '单位',
    dataIndex: 'peItemResultUnit',
    key: 'peItemResultUnit',
    align: 'left'
  },
  {
    title: '结果范围',
    dataIndex: 'reference',
    key: 'reference',
    align: 'left'
  }
  // {
  //   title: '结论',
  //   dataIndex: 'qualitative',
  //   key: 'qualitative',
  //   align: 'left',
  //   width: '15%'
  // },
  // {
  //   title: '风险等级',
  //   dataIndex: 'level',
  //   key: 'level',
  //   align: 'left'
  // }
])

const inspectColumns = ref([
  {
    title: '体检项目名称',
    dataIndex: 'peItemName',
    key: 'peItemName',
    align: 'left',
    width: '20%'
  },
  {
    title: '描述',
    dataIndex: 'peItemResult',
    key: 'peItemResult',
    align: 'left',
    width: '35%'
  },
  {
    title: '结论',
    dataIndex: 'peItemSmry',
    key: 'peItemSmry',
    align: 'left',
    width: '35%'
  }
  // {
  //   title: '风险等级',
  //   dataIndex: 'level',
  //   key: 'level',
  //   align: 'left',
  //   width: '10%'
  // }
])

const routineColumns = ref([
  {
    title: '体检项目组合名称',
    dataIndex: 'peItemGroupName',
    key: 'peItemGroupName',
    align: 'left',
    customCell: (record, index, column) => {
      return tableRowSpan(record, index, column, routineList.value)
    }
  },
  {
    title: '体检项目名称',
    dataIndex: 'peItemName',
    key: 'peItemName',
    align: 'left'
  },
  {
    title: '结果',
    dataIndex: 'peItemResult',
    key: 'peItemResult',
    align: 'left',
    width: 300
  },
  {
    title: '单位',
    dataIndex: 'peItemResultUnit',
    key: 'peItemResultUnit',
    align: 'left'
  },
  {
    title: '结果范围',
    dataIndex: 'reference',
    key: 'reference',
    align: 'left'
  }
  // {
  //   title: '结论',
  //   dataIndex: 'qualitative',
  //   key: 'qualitative',
  //   align: 'left',
  //   width: 300
  // },
  // {
  //   title: '风险等级',
  //   dataIndex: 'level',
  //   key: 'level',
  //   align: 'left'
  // }
])

const abnormalLab = ref<any>([
  {
    title: '项目组合名称',
    dataIndex: 'itemGroupName',
    key: 'itemGroupName',
    align: 'left',
    customCell: (record, index, column) => {
      return tableRowSpan(
        record,
        index,
        column,
        abnormalData.value.find((vo) => vo.name === '实验室检查').list
      )
    }
  },
  {
    title: '项目名称',
    dataIndex: 'itemName',
    key: 'itemName',
    align: 'left'
  },
  {
    title: '结果',
    dataIndex: 'itemResult',
    key: 'itemResult',
    align: 'left'
  },
  {
    title: '提示',
    dataIndex: 'resultFlag',
    key: 'resultFlag',
    align: 'left'
  },
  {
    title: '单位',
    dataIndex: 'itemResultUnit',
    key: 'itemResultUnit',
    align: 'left'
  },
  {
    title: '参考范围',
    dataIndex: 'reference',
    key: 'reference',
    align: 'left'
  }
])

const tabsIndex = ref('主要异常结果')

const tabsData = ref(['主要异常结果', '体格检查', '实验室检查', '其他辅助检查'])

const pdfUrl = ref()
const init = (id) => {
  pdfUrl.value = ''
  relationTime.value = []
  relationData.value = []
  loading.value = false
  List.value = {}
  relationTimePer.value = true
  relationTimeNext.value = false
  relationTimePage.value = 1
  relationSelTime.value = ''
  relationIndex.value = 0
  patientEmpi.value = id
  examInfoData.value = []
  tabsIndex.value = '主要异常结果'
  getPatientCheckUpTime({ empi: id })
    .then((res) => {
      List.value = res.data
      const keys = Object.keys(res.data).sort()
      relationTimeList.value = keys
      if (relationTimeList.value.length > 0) {
        if (relationTimeList.value.length > 5) {
          relationTimeNext.value = false
        } else {
          relationTimeNext.value = true
        }
        relationTimePage.value = Math.ceil(relationTimeList.value.length / 5)
        if (relationTimePage.value > 1) {
          relationTimePer.value = false
          relationTimeNext.value = true
        }
        relationTime.value = relationTimeList.value.slice(
          5 * (relationTimePage.value - 1),
          5 * relationTimePage.value
        )

        relationSelTime.value = relationTime.value[relationTime.value.length - 1]
        relationIndex.value = relationTime.value.length - 1
        getPatientCheckUpByTime()
      } else {
        relationTimePer.value = true
        relationTimeNext.value = true
      }
    })
    .catch(() => {
      relationTimePer.value = true
      relationTimeNext.value = true
    })
}

const peHistory = ref()
const peItemLabel = (data: any) => {
  nextTick(() => {
    peHistory.value.init(
      data,
      tabsIndex.value,
      patientEmpi.value,
      List.value[relationSelTime.value][0].reportNo
    )
  })
}

// 前5个时间点
const perTime = () => {
  if (relationTimePer.value) {
    //
  } else {
    // relationIndex.value = 0
    relationTimePage.value = relationTimePage.value - 1
    relationTime.value = relationTimeList.value.slice(
      5 * (relationTimePage.value - 1),
      5 * relationTimePage.value
    )
    if (relationTimePage.value == 1) {
      relationTimePer.value = true
    } else {
      relationTimePer.value = false
    }
    relationTimeNext.value = false

    relationSelTime.value = relationTime.value[relationTime.value.length - 1]

    relationIndex.value = relationTime.value.length - 1
    tabsIndex.value = '主要异常结果'
    getPatientCheckUpByTime()
  }
}

// 后5个时间点
const nextTime = () => {
  if (relationTimeNext.value) {
    //
  } else {
    // relationIndex.value = 0
    relationTimePage.value = relationTimePage.value + 1
    relationTime.value = relationTimeList.value.slice(
      5 * (relationTimePage.value - 1),
      5 * relationTimePage.value
    )
    relationTimePer.value = false
    // 向上取整
    if (Math.ceil(relationTimeList.value.length / 5) == relationTimePage.value) {
      relationTimeNext.value = true
    } else {
      relationTimeNext.value = false
    }

    relationSelTime.value = relationTime.value[relationTime.value.length - 1]

    relationIndex.value = relationTime.value.length - 1
    tabsIndex.value = '主要异常结果'
    getPatientCheckUpByTime()
  }
}

// 时间点 点击
const relationTimeHandle = (data, index) => {
  relationIndex.value = index
  relationSelTime.value = data
  tabsIndex.value = '主要异常结果'
  getPatientCheckUpByTime()
}

const examInfoOrgName = ref('')
const examInfoUrl = ref('')
// 获取某个日期的体检信息
const getPatientCheckUpByTime = () => {
  loading.value = true
  examInfoData.value = []
  testList.value = []
  inspectList.value = []
  routineList.value = []
  examInfoUrl.value = ''
  const data = List.value[relationSelTime.value]
  pdfUrl.value = ''
  if (data && data.length) {
    console.log(data)
    loading.value = false
    examInfoUrl.value = data[0].url
    const peItemList = data[0].peItemList
    examInfoOrgName.value = data[0].orgName
    const abnormalItem = JSON.parse(data[0].abnormalItem) // 主要异常结果
    testList.value = Object.prototype.hasOwnProperty.call(peItemList, '实验室检查')
      ? peItemList['实验室检查']
      : []
    inspectList.value = Object.prototype.hasOwnProperty.call(peItemList, '辅助检查')
      ? peItemList['辅助检查']
      : []
    routineList.value = Object.prototype.hasOwnProperty.call(peItemList, '常规检查')
      ? peItemList['常规检查']
      : []

    if (abnormalItem) {
      const abnormalLIst = abnormalItem.map((item) => {
        return {
          ...item,
          content: JSON.parse(item.content)
        }
      })

      abnormalData.value = groupByItemTypeName(abnormalLIst, 'itemTypeName')
        .map((vo) => {
          return {
            ...vo,
            name: vo.name.replace('常规检查', '体格检查').replace('辅助检查', '其他辅助检查'),
            data: groupByItemTypeName(vo.list, 'itemGroupName')
          }
        })
        .reverse()
      console.log(abnormalData.value)
    } else {
      abnormalData.value = []
    }

    // 健管报告
    getHealthReportStatus({
      empi: patientEmpi.value,
      reportNo: data[0].reportNo
    }).then((res) => {
      if (res.data) {
        pdfUrl.value = res.data
      }
    })
  }
}

const groupByItemTypeName = (arr: any, itemName: any) => {
  const map = new Map()

  arr.forEach((item: any) => {
    const key = item[itemName]
    if (!map.has(key)) {
      map.set(key, [])
    }
    map.get(key)!.push(item)
  })

  const result = Array.from(map.entries()).map(([key, value]) => ({
    name: key,
    list: value
  }))

  return result
}

const seeFile = () => {
  window.open(examInfoUrl.value)
}

const healthFile = () => {
  window.open(pdfUrl.value)
}

defineExpose({
  init
})
</script>
<style lang="less" scoped>
.title-box {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 32px;
  margin: 0 0 10px;
  font-weight: 600;
  line-height: 32px;
  color: #1d2129;

  .title-item-left {
    font-size: 18px;
    font-weight: 600;
  }

  .text-icon {
    display: inline-block;
    width: 3px;
    height: 16px;
    margin-right: 8px;
    line-height: 32px;
    background: #165dff;
  }
}

.health-info .ant-form-item {
  margin-bottom: 10px;
}

.title-item {
  width: 100%;
  height: 32px;
  padding-left: 16px;
  margin: 24px 0 12px;
  font-size: 16px;
  font-weight: 600;
  line-height: 32px;
  color: #1d2129;
  background: #f7f8fa;
}

.orgName {
  font-weight: 600;
}

.pe-time-li {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 96px;
  height: 55px;
  margin: 0 6px;
  cursor: pointer;
  background: #f2f3f5;
  border-radius: 4px;
}

.pe-time-year {
  color: #333;
}

.pe-time-date {
  font-size: 13px;
  color: #666;
}

.pe-time-li.action {
  position: relative;
  background-color: #165dff;

  .pe-time-year {
    color: #fff;
  }

  .pe-time-date {
    color: #fff;
  }
}

.action::before {
  position: absolute;
  bottom: -16px;
  left: 50%;
  display: block;
  margin-left: -10px;
  content: '';
  border-color: #165dff transparent transparent;
  border-style: solid dashed dashed;
  border-width: 10px;
}

.pe-item-col {
  color: rgb(22, 93, 255);
  cursor: pointer;
}
</style>
<style>
.exam-table .ant-table-container table > thead > tr:first-child > *:first-child {
  background-color: #e5e6eb;
}

/* 第二个 */
.exam-table .ant-table-container table > thead > tr:first-child > *:nth-child(2) {
  background-color: #dbdde1;
}

/* 第三个 */
.exam-table .ant-table-container table > thead > tr:first-child > *:nth-child(3) {
  background-color: #ccd0d6;
}

.abnormal-label {
  display: flex;
  align-items: center;
  height: 38px;
  padding-left: 16px;
  margin-top: 24px;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #165dff;
  background: #e8f3ff;
}

.abnormal-label:nth-of-type(1) {
  margin-top: 0;
}

.group-label {
  margin: 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.group-cont {
  padding: 12px;
  margin-top: 12px;
  color: #1d2129;
  background: #f7f8fa;
}
</style>
